from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.shortcuts import HttpResponseRedirect

from Buyer.models import *
from Store.models import *
from Qshop.views import myPay
from Qshop.views import setPassword


def register(request):
    if request.method == "POST":
        username = request.POST.get("user_name")
        password = request.POST.get("user_pwd")
        email = request.POST.get("user_email")
        # 保存用户
        user = QUser()
        user.username = username
        user.password = setPassword(password)
        user.has_store = 0
        user.save()
        # 保存用户详情
        user_info = QuserInfo()
        user_info.nick_name = username
        user_info.email = email
        user_info.user_id = user
        user_info.save()
        return HttpResponseRedirect("/buyer/login/")
    return render(request, "buyer/bootstrap_register.html")


def r_ajax(request):
    result = {'data': ''}
    u_name = request.GET.get('user_name')
    data = QUser.objects.filter(username=u_name)
    if data:
        result['data'] = '用户已存在'

    return JsonResponse(result)


def login(request):
    if request.method == 'POST':
        u_name = request.POST.get('user_name')
        u_pwd = setPassword(request.POST.get('user_pwd'))

        user = QUser.objects.filter(username=u_name).first()
        if user:
            if u_pwd == user.password:
                response = redirect('/buyer/index/')
                response.set_cookie('user_id', user.id)
                return response

    return render(request, "buyer/bootstrap_login.html")


def index(request):
    goods = Goods.objects.all()
    return render(request, "buyer/index.html", locals())


def detail(request, g_id):
    goods = Goods.objects.get(id=int(g_id))
    return render(request, "buyer/detail.html", locals())


def pay(request):
    order_id = request.GET.get('order_id')
    money = request.GET.get('money')
    if order_id and money:
        url = myPay(order_id, money)  # 请求支付
    else:
        url = '/'
    return HttpResponseRedirect(url)  # 支付完成跳转到支付成功页


from Qshop.sms.example.sendcode import send_code


def pay_success(request):
    order_id = request.GET.get('out_trade_no')
    order = Order.objects.get(order_id=order_id)
    order.order_statue = '已支付'
    order.save()
    send_code('200')
    return render(request, "buyer/pay_success.html")


def add_cart(request):
    result = {
        'code': 500,
        'data': "商品添加成功"
    }
    if request.method == "POST":
        goods_id = int(request.POST.get('goods_id'))
        goods_number = int(request.POST.get('goods_number'))
        user_id = int(request.COOKIES.get("user_id"))
        if user_id:
            if goods_id:
                if goods_number:
                    user = QUser.objects.filter(id=int(user_id)).first()
                    goods = Goods.objects.filter(id=int(goods_id)).first()
                    if user and goods:
                        cart = Car.objects.filter(goods_id=goods, user_id=user)  # 判断购物车是否够有数据
                        if not cart:
                            cart = Car()
                        cart.goods_id = goods
                        cart.user_id = user

                        if cart.c_goods_number:  # 如果购物车的商品数量不为0
                            cart.c_goods_number += goods_number  # 商品数量叠加
                        else:
                            cart.c_goods_number = goods_number  # 商品第一个添加到购物车

                        if cart.c_goods_number <= goods.goods_number:
                            cart.save()
                            result['code'] = 200
                        else:
                            result['data'] = "没那么多商品"
                    else:
                        result['data'] = "非法请求"
                else:
                    result['data'] = "至少有一个商品"
            else:
                result['data'] = '至少选择一个商品'
        else:
            result['data'] = '请先登录'
    return JsonResponse(result)


def cart(request):
    user_id = request.COOKIES.get('user_id')
    user = QUser.objects.filter(id=int(user_id)).first()
    car_list = user.car_set.all()  # 当前用户的购物车信息
    total_price = 0
    sum = 0
    for c in car_list:
        num = c.c_goods_number
        price = c.goods_id.goods_price
        total_price += num*price
        sum += 1
    return render(request, "buyer/cart.html", locals())


def place_order(request):
    # 从前端获取数据
    total = request.GET.get(id('total'))
    print(total)

    # 获取用户id
    user_id = request.COOKIES.get('user_id')
    adr = Address.objects.filter(user_id=int(user_id)).first()

    order = Order()
    order.order_id = 100001,
    order.g_type_number = total
    return render(request, 'buyer/place_order.html', locals())


def change_car_num(request):
    """
     购物车订单页面的购买数量的加减按钮
    """
    cart_id = request.GET.get('cart_id')
    count = request.GET.get('count')
    # amount = request.GET.get('amount')

    # 查询数据库，修改数量
    car = Car.objects.get(id=cart_id)
    car.c_goods_number = int(count)
    car.save()
    return JsonResponse('{"state": "0"}', safe=False)




